#! /usr/bin/env python

import signal

from taskqueue import TaskQueue
from frequency import Frequency
from responser import Responser
from contractor import Contractor

if __name__ == '__main__':
    srv_shutdown        = False
    graceful_shutdown   = False
    def sighandler(signum, frame):
        if signum == signal.SIGTERM:
            srv_shutdown = True
        elif signum == signal.SIGINT:
            graceful_shutdown = True

    signal.signal(signal.SIGTERM, sighandler)
    signal.signal(signal.SIGINT, sighandler)

    taskqueue = TaskQueue()

    responser = Responser()
    responser.spawn()

    frequency = Frequency((32, 64, 128, 256, 512, 1024))

    contractor = Contractor(program, number, stderr)
    contractor.recruit()
    contractor.trial()

    while not graceful_shutdown and not srv_shutdown:
        for i in xrange(contractor.idle_count()):
            try:
                id, task = taskqueue.get()
                frequency.reset()
                contractor.assign_task(id, task)
                timeout = -1
            except TaskQueueError:
                # taskqueue and taskcentre are empty.
                timeout = frequency.time()
                break

        contractor.handle_resign()
        contractor.recruit()

        contractor.wait_response(timeout)

        taskqueue.complete(results)

    if graceful_shutdown:
        contractor.quit_graceful()
    else:
        contractor.quit()
